import axios from 'axios'
import { useUserStore } from '@/stores'
import { message } from 'ant-design-vue'

const http = (config) => {
  const request = axios.create({
    baseURL: import.meta.env.VITE_PROXY,
    timeout: 50000,
    headers: {
      // 'Access-Control-Allow-Origin': '*',
      // 'Cache-Control': 'no-cache',
      // 'Content-Type': 'application/json',
    },
  })
  // 请求拦截器
  request.interceptors.request.use(
    (config) => {
      return config
    },
    (err) => {
      return Promise.reject(err)
    },
  )
  // 响应拦截器
  request.interceptors.response.use(
    (res) => {
      const { status, statusText, data } = res
      if (status === 200) {
        if (data.code === 0) {
          // 返回数据
          return data.data
        } else {
          message.error(data.message)
          return Promise.reject(data)
        }
      } else {
        message.error(statusText)
        return Promise.reject(statusText)
      }
    },
    (err) => {
      message.error(err)
      return Promise.reject(err)
    },
  )
  return request(config)
}

/**
 * GET 请求
 * @param {*} url
 * @param {*} params
 */
export const httpGet = (url, params) => {
  return http({
    url,
    method: 'GET',
    params,
  })
}
/**
 * POST 请求
 * @param {*} url
 * @param {*} params
 */
export const httpPost = (url, data) => {
  const { userInfo } = useUserStore()
  return http({
    url,
    method: 'POST',
    data: {
      user_token: userInfo.user_token,
      ...data,
    },
  })
}
/**
 * PUT 请求
 * @param {*} url
 * @param {*} params
 */
export const httpPut = (url, data) => {
  const { userInfo } = useUserStore()
  return http({
    url,
    method: 'PUT',
    data: {
      user_token: userInfo.user_token,
      ...data,
    },
  })
}
/**
 * DELETE 请求
 * @param {*} url
 * @param {*} params
 */
export const httpDelete = (url, data) => {
  const { userInfo } = useUserStore()
  return http({
    url,
    method: 'DELETE',
    data: {
      user_token: userInfo.user_token,
      ...data,
    },
  })
}

export default http
